<?php

namespace app\wechat\controller;

use app\wechat\controller\Openid;
use EasyWeChat\Kernel\Messages\Media;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Text;
use Pheanstalk\Pheanstalk;

// 客服消息相关
class Cuspheanstalk
{
    public $ser;
    public $openPlatform;
    public $openidRedis;

    // 初始化操作
    public function __construct()
    {
        $this->ser = new Pheanstalk('127.0.0.1');
        $this->openPlatform = app('wechat.open_platform');
        $this->openidRedis = new Openid();
        set_time_limit(0);
    }

    // 通过appid获取公众号实例
    public function get_official_account($appid)
    {
        $authinfo = $this->openPlatform->getAuthorizer($appid)['authorization_info'];
        $authtoken = $authinfo['authorizer_refresh_token'];
        $officialAccount = $this->openPlatform->officialAccount($appid, $authtoken);
        return $officialAccount;
    }

    // 处理图片链接消息
    public function handleItems($items)
    {
        $new = array();
        foreach ($items as $item) {
            $new_item = new NewsItem([
                'title' => $item['title'],
                'description' => '...',
                'url' => $item['url'],
                'image' => $item['image'],
            ]);
            array_push($new, $new_item);
        }

        return new News($new);
    }

    public function start()
    {
        echo 'start';

        while (1) {
            // 监听send管道
            $job = $this->ser->watch('customer')->ignore('default')->reserve();

            // 获取任务数据
            $arr = json_decode($job->getData(), true);

            $appid = $arr['appid'];
            $data = $arr['data'];
            $type = $arr['type'];
            $openid_list = $arr['openid_list'];

            $officialAccount = $this->get_official_account($appid);

            if ($type == 'media') {
                $msg = new Media($data['meida_id'], $data['media_type']);
            } elseif ($type == 'image') {
                $msg = $this->handleItems($data);
            } else {
                $msg = new Text($data);
            }

            // 循环发送
            foreach ($openid_list as $openid) {
                $result = $officialAccount->customer_service->message($msg)->to($openid)->send();
                if ($result['errcode'] == 0) {
                    $this->openidRedis->add_openid($appid, $openid);
                }
            }

            // 删除任务
            $this->ser->delete($job);
            usleep(100);
        }
    }

}

$server = new Cuspheanstalk();
$server->start();
